#!/usr/bin/env python
# coding:utf-8

from symbol_table import symbol_table


def execute(client, parse_info):
    """
    Discussion about the transformation from #n to real id?
    """
    warning_message = []
    transform_result = transform_parse_info(parse_info)
    return_type = ""
    result = None
    if transform_result is False:
        warning_message.append('Error in user or group information')
        return_type = 'error'


    # Dispatch to corresponding function
    if parse_info['cmd'] == "show_wb":
        result = show_wb(client, parse_info['user'], parse_info['group'])
        return_type = 'weibo'

    elif parse_info['cmd'] == "show_following":
        uid = symbol_table.uid
        result = show_following(client, uid)
        return_type = 'user'

    elif parse_info['cmd'] == "follow_user":
        pass
        #result = follow_user(client)

    elif parse_info['cmd'] == "send_wb":
        #msg = parse_info['content']
        msg = '我的微博'
        msg = parse_info['content']
        pic_path = parse_info['picture']
        result = send_wb(client, msg, pic_path)
        return_type = 'no_type'


    elif parse_info['cmd'] == 'send_comment':
        # msg = parse_info['content']
        msg = '好吧好烂的API...'
        msg = parse_info['content']
        wb_id = parse_info['weibo']

        if 'comment' in parse_info:
            comment_id = parse_info['comment']
        else:
            comment_id = None


        result = send_comment(client, msg, wb_id, comment_id)
        return_type = 'no_type'


    elif parse_info['cmd'] == 'show_groups':
        result = show_groups(client)
        return_type = 'group'

    elif parse_info['cmd'] == 'show_comment':
        result = show_comment(client, parse_info['weibo'])
        return_type = 'comment'

    elif parse_info['cmd'] == "TODO":
        pass

    #-------Return information to upper layer
    if result == None:
        warning_message.append(parse_info['cmd'] + ' failed')
        return {'state':False, 'warning_message': warning_message, 'return_type':return_type}
    else:
        return {'state':True, 'warning_message':warning_message, 'result':result, 'return_type':return_type}


def transform_parse_info(parse_info):
    # Change from #n to real ids
    # False -> Transformation error
    if 'user' in parse_info and parse_info['user'] != None:
        #parse_info['user'] = symbol_table.get_user(parse_info['user'])
        if parse_info['user'] == None:
            return False
        else:
            parse_info['user'] = int(parse_info['user'])

    if 'group' in parse_info and parse_info['group'] != None:
        #parse_info['group'] = symbol_table.get_group(parse_info['group'])
        if parse_info['group'] == None:
            return False
        else:
            parse_info['group'] = int(parse_info['group'])

    if 'weibo' in parse_info and parse_info['weibo'] != None:
        if parse_info['weibo'] == None:
            return False
        else:
            parse_info['weibo'] = int(parse_info['weibo'])
        parse_info['weibo'] = symbol_table.get_weibo(parse_info['weibo'])

    if 'comment' in parse_info and parse_info['comment'] != None:
        if parse_info['comment'] == None:
            return False
        else:
            parse_info['comment'] = int(parse_info['comment'])
        parse_info['comment'] = symbol_table.get_group(parse_info['comment'])

    return True


#---------------------- Real execution ---------------------------------------#


def show_wb(client, user_id = None, group_id = None):
    """
    Function for showing weibo

    client: Login Object
    user_id # Change to screen name?
    group_id: list_id

    Todo:
    group function untested
    """

    try:
        if user_id == None and group_id == None:
            # OK
            posts = client.statuses.friends_timeline.get()["statuses"]
        elif user_id != None:
            # OK
            # Fuck! The related API is not allowed by sina now
            posts = client.statuses.friends_timeline.get()["statuses"]
            
        else:
            posts = client.friendships.groups.timeline.get(list_id = group_id)["statuses"]
        return posts
    except Exception, e:
        return None


def follow_user(client, user_id, group_id = None):
    try:
        user = client.friendships.create.post(uid = user_id)
        if group_id != None:
            client.friendships.groups.members.add.post(uid = user_id, list_id = group_id)
        return user
    except Exception, e:
        return None


def show_following(client, user_id, group_id = None):
    # User_id here must be the id of the app user
    # which is gotten in the initialization
    try:
        if group_id == None:
            # OK
            users = client.friendships.friends.get(uid = user_id )["users"]
        else:
            users = client.friendships.groups.members.get(list_id = group_id)["users"]
        return users
    except Exception, e:
        return None

    
def send_wb(client, msg, pic_path = None):
    try:
        if pic_path == None:
            # OK
            client.statuses.update.post(status=msg)
        else:
            # OK
            client.statuses.upload.post(status = msg, pic = open(pic_path,"rb"))
        return 'No message from SINA'

    except Exception, e:
        return None

def send_comment(client, msg, wb_id, comment_id):
    try:
        if comment_id == None:
            # OK
            client.comments.create.post(id = wb_id, comment = msg)
        else:
            # OK
            client.comments.reply.post(cid = comment_id, id = wb_id, comment = msg)

        return 'No message from SINA'
    except Exception, e:
        return None




def show_comment(client, _id):
    try:

        comments = client.comments.show.get(id = _id)['comments']
        return comments
    except Exception, e:
        return None

def show_groups(client):
    try:
        # Fuck SINA! Need authorization
        groups = client.friendships.groups.get()
        return groups['lists']
    except Exception, e:
        return None

